#!/usr/bin/python
#
# This file is part of the LyricZilla project.
# http://lyriczilla.googlecode.com/
#
# Copyright (c) 2007 Liu Qishuai
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#

import gobject
import os
import os.path
import sys
import dbus
import dbus.service
import dbus.mainloop.glib
import time
import lyriczilla.service
import lyriczilla.util
import lyriczilla.player
import urllib2
import cPickle
import md5

class LyricZilla(dbus.service.Object):


	def __dump_object(self, obj, filename):
		try:
			os.makedirs(os.path.dirname(filename))
		except:
			pass
		try:
			cPickle.dump(obj, open(filename, 'w'))
		except:
			pass
	
	def __load_object(self, objtype, filename):
		try:
			return objtype(cPickle.load(open(filename)))
		except:
			return None


	def __dump_text(self, text, filename):
		try:
			os.makedirs(os.path.dirname(filename))
		except:
			pass
		try:
			open(filename, 'w').write(text.encode('utf-8'))
		except Exception, e:
			pass

	def __load_text(self, filename):
		try:
			return open(filename).read()
		except:
			return None

	@dbus.service.method("com.googlecode.LyricZilla.Service",
		in_signature='bsss', out_signature='aa{ss}', async_callbacks=('_succ','_fail'))
		
	def GetLyricList(self, cacheable, filename, title, artist, _succ, _fail):
		home_dir = os.environ['HOME']
		
		# if i found a local lrc file, load it first.
		
		#files = (
		#	home_dir + '/.lyriczilla/lyric/' + '%s - %s.lrc' % (title, artist),
			
			
		
		cache_filename = home_dir + '/.lyriczilla/cache/list/%s - %s.list' % (artist, title)
		l = None
		if cacheable:
			l = self.__load_object(list, cache_filename)
		
		if l != None:
			_succ(l)
		else:
			try:
				l = lyriczilla.service.get_lyric_list(title, artist)
				self.__dump_object(l, cache_filename)

				_succ(l)
			except:
				_fail(1)
				
	@dbus.service.method("com.googlecode.LyricZilla.Service",
		in_signature='bs', out_signature='a(is)', async_callbacks=('_succ','_fail'))
			
	def GetLyric(self, cacheable, url, _succ, _fail):
		home_dir = os.environ['HOME']
		
		cache_filename = home_dir + '/.lyriczilla/cache/lyric/' + md5.md5(url.encode('utf-8')).hexdigest() + '.lrc'
		
		lrc_text = None
		if cacheable:
			lrc_text = self.__load_text(cache_filename)
			
		if lrc_text == None:
			try:
				lrc_text = lyriczilla.service.get_lyric_source(url)
				self.__dump_text(lrc_text, cache_filename)
			except:
				pass
				
		if lrc_text != None:
			try:
				l = lyriczilla.util.lrctolist(lrc_text)
				_succ(l)
			except:
				_fail(1)
		else:
			_fail(1)

	@dbus.service.method("com.googlecode.LyricZilla.Player",
		in_signature='', out_signature='a{ss}')
	def GetInfo(self):
		info = lyriczilla.player.get_info()
		if info != None:
			enc = 'utf-8'
			return {
				'title': str(info['title'].encode(enc)),
				'artist': str(info['artist'].encode(enc)),
				'time': str(info['time']),
				'uri': str(info['uri'].encode(enc)),
			}


if __name__ == '__main__':
	dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
	
	session_bus = dbus.SessionBus()
	
	name = dbus.service.BusName("com.googlecode.LyricZilla", session_bus)
	object = LyricZilla(session_bus, '/com/googlecode/LyricZilla')

	mainloop = gobject.MainLoop()
	print 'Running LyricZilla service.'
	
	lyriczilla.player.__scan()
	
	mainloop.run()


